package com.atguigu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;

/**
 * 处理用户注册的Servlet
 */
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//获取用户名、密码和邮箱
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		//创建UserDao对象
		UserDao userDao = new UserDaoImpl();
		//调用UserDao中验证用户名是否存在的方法
		boolean flag = userDao.checkUsername(username);
		if(flag) {
			//用户名已存在，设置一个提示信息并放到request域中
			request.setAttribute("msg", "用户名已存在！");
			//转发到注册页面
			request.getRequestDispatcher("/pages/regist.jsp").forward(request, response);
		}else {
			//用户名可用，将用户信息保存到数据库中
			userDao.saveUser(username, password, email);
			//重定向到登录页面
			response.sendRedirect(request.getContextPath()+"/pages/login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
